<?php

namespace app\admin\model\shop\user;

use think\Model;

/**
 * Commission
 */
class Commission extends Model
{
    const TYPE_ORDER = 1;     //陪玩订单分佣
    const TYPE_DISTRIBUTION = 2;    //订单分销
    const TYPE_Withdrawal = 3;    //提现

    const TYPE_Withdrawal_Return = 4; //提现退还


    // 表名
    protected $name = 'shop_user_commission';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    public function getChangePriceAttr($value): float
    {
        return (float)$value;
    }

    public function getBeforePriceAttr($value): float
    {
        return (float)$value;
    }

    public function getAfterPriceAttr($value): float
    {
        return (float)$value;
    }

    public function shopOrder(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\shop\order\Order::class, 'shop_order_id', 'id');
    }

    public function shopUser(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\shop\user\User::class, 'shop_user_id', 'id');
    }

    /**
     * 余额变动记录
     * @param $user_id  //当前用户id,当是店铺的时候，取店铺创始人的user_id
     * @param $type     //类型
     * @param $money    //金额，永远是正的
     * @param string $source_id //资源id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change($user_id, $type, $money, $source_id = "",  $memo = '')
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => '操作成功'
        ];
        \think\facade\Db::startTrans();
        try {
            if($money != 0)
            {
                //取用户实际余额
                $userModel = new User();
                $userInfo = $userModel->where([ 'id' => $user_id ])->find();
                if(!$userInfo)
                {
                    $result['msg'] = '没有找到此用户';
                    return $result;
                }

                if(!$memo){
                    //取描述，并简单校验
                    $re = $this->getMemo($type, $money);
                    if(!$re['status'])
                    {
                        return $re;
                    }
                    $memo = $re['data'];
                }

                (float)$money = abs($money);
                //如果是减余额的操作，还是加余额操作
                if($type == self::TYPE_Withdrawal)
                {
                    $money = - $money;
                }

                if($type == self::TYPE_Withdrawal_Return)
                {
                    $money =  $money;
                }

                if($type == self::TYPE_ORDER || $type == self::TYPE_DISTRIBUTION)
                {
                    $money = + $money;
                }
                $balance = (float)$userInfo[ 'commission' ] + (float)$money;
                if(($balance) < 0)
                {
                    $result['msg'] = '佣金不足';
                    return $result;
                }
                $data['shop_order_id'] = $source_id;
                $data['shop_user_id'] = $user_id;
                $data['status'] = $type;
                $data['change_price'] = $money;
                $data['before_price'] = $userInfo[ 'commission' ];
                $data['after_price'] = $balance;
                $data['desc'] = $memo;
                $data['create_time'] = time();
                $info = $this->where('shop_order_id',$source_id)->where('shop_user_id',$user_id)->where('status',$type)->find();
                if(!isset($info) || $source_id == ''){
                    $this->insert($data);
                    //上面保存好主体表，下面保存明细表
                    $userInfo->commission = $data['after_price'];
                    $userInfo->save();
                }
            }
            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
            $result['status']  = false;
            $result['msg']  = $e->getMessage();
            return $result;
        }
        $result['status'] = true;
        return $result;
    }

    /**
     * 取得描述，并做简单校验
     * @param $type
     * @param $money
     * @param string $source_id
     * @param string $cate_money
     * @return array|mixed
     */
    private function getMemo($type, $money)
    {
        $result = [
            'status' => true,
            'data' => [],
            'msg' => ''
        ];
        $desc = '元';
        switch($type)
        {
            case self::TYPE_ORDER:
                $result['data'] = '订单分佣' . $money . $desc;
                break;
            case self::TYPE_DISTRIBUTION:
                $result['data'] = '订单分销' . $money . $desc;
                break;
            case self::TYPE_Withdrawal:
                $result['data'] = '提现' . $money . $desc;
                break;
            case self::TYPE_Withdrawal_Return:
                $result['data'] = '提现退还' . $money . $desc;
                break;
            default:
                $result['status'] = false;
                $result['msg'] = '变动失败';
                return $result;
        }
        return $result;
    }
}